package cn.tedu.atomic;

import java.util.concurrent.CountDownLatch;
import java.util.concurrent.atomic.AtomicInteger;

public class AtomicIntegerDemo {
//    static int i = 0;
    static AtomicInteger ai = new AtomicInteger(0);

    public static void main(String[] args) throws InterruptedException {
        CountDownLatch cd1 = new CountDownLatch(2);
        new Thread(new Add(cd1)).start();
        new Thread(new Add(cd1)).start();

        // 上面累加完成之后,才能打印i的值
        cd1.await();
        System.out.println(ai);
    }
}

class Add implements Runnable {
    private CountDownLatch cd1;

    public Add(CountDownLatch cd1) {
        this.cd1 = cd1;
    }

    @Override
    public void run() {
        synchronized (Add.class) {
            for (int i = 0; i < 10000; ++i) {
//                AtomicIntegerDemo.i++;
                AtomicIntegerDemo.ai.getAndIncrement();
            }
        }
        cd1.countDown();
    }
}
